<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\logic\AdminUserLogic;
use app\common\logic\DepartmentLogic;
use League\Flysystem\FileNotFoundException;
use plugins\upload\controller\UploadPlugin;
use think\facade\Event;
use think\facade\Request;

/**=========================================
 * Copyright © 2023-2024, WICMS.CN. All Rights Reserved
 * Project Name: WiCMS
 * Description: 管理用户控制器
 * Author: jason
 * Email: 52527998@QQ.COM
 * Date: 2024/10/12
 * Time: 下午5:04
 * File: app\admin\controller\User.php
 * =========================================
 */
class User extends BaseModule
{

    public function initialize(): void
    {
        parent::initialize();
    }

    public function get_list(): void
    {
        $department_id = Request::get('department_id/d', 0);
        $mobile        = Request::get('mobile/d');
        $status        = Request::get('status');
        $username      = Request::get('username/s');
        $condition     = [];
        if ($department_id && $department_id > 0) {
            // 取当前部门所有下级部门
            $departmentIds = DepartmentLogic::getDepartmentChildIds($department_id);
            $condition[] = ['department_id', 'in', $departmentIds];
        }
        if ($mobile) {
            $condition[] = ['mobile', 'like', '%' . $mobile . '%'];
        }
        if ($status != '' && $status != -1) {
            $condition[] = ['status', '=', $status];
        }
        if ($username) {
            $condition[] = ['username', 'like', '%' . $username . '%'];
        }
        $list = AdminUserLogic::getList($condition);
        $this->success('获取成功', $list);
    }

    public function login(): void
    {
        $username    = Request::post('username/s');
        $password    = Request::post('password/s');
        $captcha     = Request::post('captcha/s', '');
        $captchaCode = Request::post('captchaCode/s', '');
        // 判断提交参数是否全部存在
        if (empty($username) || empty($password)) {
            $this->error('参数错误', 500);
        }
        $result = AdminUserLogic::Login($username, $password, $captcha, $captchaCode);
        if (!is_array($result)) {
            $this->error($result, 0);
        }
        $this->success('登录成功', $result);
    }

    // 交换token
    public function refresh_token(): void
    {
        $result = AdminUserLogic::refreshToken();
        if (is_array($result)) {
            $this->success('success', $result);
        } else {
            $this->error($result);
        }
    }


    public function get_user_roles(): void
    {
        $user_id = Request::get('user_id/d');
        if (empty($user_id)) {
            $this->error('参数不能为空！');
        }
        $result = AdminUserLogic::getUserRoles($user_id);
        $this->success('success', $result);
    }

    public function set_user_roles(): void
    {
        $user_id  = Request::post('user_id/d');
        $role_ids = Request::post('role_ids/a');
        if (empty($user_id) || empty($role_ids)) {
            $this->error('参数不能为空！');
        }
        $result = AdminUserLogic::setUserRoles($user_id, $role_ids);
        if ($result === true) {
            Event::trigger('setAdminUserRolesSuccess', ['user_id' => $user_id]);
            $this->success('success');
        } else {
            $this->error($result);
        }
    }

    /**
     * 设置用户头像
     *
     * @return void
     * @throws FileNotFoundException
     */
    public function set_user_avatar(): void
    {
        $user_id = Request::post('user_id/d');
        $avatar  = Request::post('avatar/s');
        if (empty($user_id) || empty($avatar)) {
            $this->error('参数不能为空！');
        }
        $result = UploadPlugin::do_upload('base64', 'avatar', $avatar);
        if ($result['code'] == 0) {
            $this->error($result['message']);
        }
        $userData = [
            'id'     => $user_id,
            'avatar' => $result['data']['url']
        ];
        $result   = AdminUserLogic::updateUserField($userData);
        if ($result === true) {
            $this->success('success');
        } else {
            $this->error('头像保存失败');
        }
    }

    /**
     * 更新用户信息
     *
     * @return void
     */
    public function save_data(): void
    {
        $data   = Request::post('');
        $result = AdminUserLogic::updateUserInfo($data);
        if ($result === true) {
            $this->success('success');
        } else {
            $this->error($result);
        }
    }

    /**
     * 更新用户密码
     */
    public function set_password(): void
    {
        $data     = Request::post('');
        $userData = [
            'id'       => $data['id'],
            'password' => md5(sha1($data['password']))
        ];
        $result   = AdminUserLogic::updateUserField($userData);
        if ($result === true) {
            Event::trigger('setAdminUserPasswordSuccess', ['user_id' => $data['id']]);
            $this->success('success');
        } else {
            $this->error($result);
        }
    }

    /**
     * 删除用户
     */
    public function delete_user(): void
    {
        $id = Request::post('id/d');
        if (empty($id)) {
            $this->error('参数不能为空！');
        }
        $result = AdminUserLogic::deleteUser($id);
        if ($result === true) {
            $this->success('success');
        } else {
            $this->error($result);
        }
    }
}